package com.dengqi.mymodule.activity.camera;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.dengqi.mymodule.tools.UriUtils;

import java.io.File;

import static android.app.Activity.RESULT_OK;

public class PhotoUtils {

    private static final int REQUEST_CODE_CAMERA = 1;
    private static final int REQUEST_CODE_ALBUM = 2;
    private static final int REQUEST_CODE_CROP = 3;
    private Context mContext;
    private boolean isCrop = true;
    //目标file，最后输出的file
    private File targetFile;
    private PhotoCallBack mPhotoCallBack;

    public PhotoUtils(Context context){
        this.mContext = context;
        //存在外部私有路径，软件卸载后删除
        this.targetFile = new File(context.getExternalFilesDir("camera"), "target.jpg");
    }

    public void setIsCrop(boolean isCrop){
        this.isCrop = isCrop;
    }

    public void setCallBackListener(PhotoCallBack mPhotoCallBack){
        this.mPhotoCallBack = mPhotoCallBack;
    }

    public void startCamare() {
        //目标file转成uri
        Uri targetUri = UriUtils.file2Uri(mContext, targetFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //将拍照结果保存至Uri中
        //7.0uri申请写入权限，只能写在MediaStore.EXTRA_OUTPUT前面
        boolean isSuccess = UriUtils.applyUri(mContext, intent, targetUri);
        if (isSuccess) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
            ((Activity)mContext).startActivityForResult(intent, REQUEST_CODE_CAMERA);
        }
    }

    private void startCrop(File sourceFile) {
        //file->uri
        Uri sourceUri = UriUtils.file2Uri(mContext, sourceFile);
        Uri targetUri = UriUtils.file2Uri(mContext, targetFile);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(sourceUri, "image/*");
        intent.putExtra("return-data", false);
        //7.0uri申请写入权限，只能写在MediaStore.EXTRA_OUTPUT前面
        boolean isSuccess = UriUtils.applyUri(mContext, intent, targetUri);
        if (isSuccess) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            ((Activity)mContext).startActivityForResult(intent, REQUEST_CODE_CROP);
        }
    }

    public void startAlbum(){
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT) ; //"android.intent.action.GET_CONTENT"
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType( "image/*"); //查看类型 String IMAGE_UNSPECIFIED = "image/*";
        ((Activity)mContext).startActivityForResult(intent, REQUEST_CODE_ALBUM) ;
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            if(isCrop){
                startCrop(targetFile);
            } else{
                if(mPhotoCallBack!=null){
                    mPhotoCallBack.callback(targetFile);
                }
//                //由于指定了目标uri，存储在目标uri，intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
//                //目标file转成bitmap，获取1024x1024像素缩略图
//                Bitmap bitmap = BitmapUtils.file2Bitmap(targetFile, 1024, 1024);
//                imageView.setImageBitmap(bitmap);
//                //存下来只有100KB左右
//                ImageFileUtils.writeBitmap2File(bitmap, "camera.jpg");
//                //删除目标file
//                if (targetFile != null && targetFile.exists()) {
//                    targetFile.delete();
//                }
            }
        } else if (requestCode == REQUEST_CODE_CROP && resultCode == RESULT_OK) {
            if(mPhotoCallBack!=null){
                mPhotoCallBack.callback(targetFile);
            }
            //由于指定了目标uri，存储在目标uri，intent.putExtra("return-data", false);
            //目标file转成bitmap，获取1024x1024像素缩略图
//            Bitmap bitmap = BitmapUtils.file2Bitmap(targetFile, 1024, 1024); //BitmapUtils.uri2Bitmap(targetUri);
//            imageView.setImageBitmap(bitmap);
//            //存下来只有100KB左右
//            ImageFileUtils.writeBitmap2File(bitmap, "crop.jpg");
//            //删除目标file
//            if (targetFile != null && targetFile.exists()) {
//                targetFile.delete();
//            }
        } else if (requestCode == REQUEST_CODE_ALBUM && resultCode == RESULT_OK) {
            String imagePath = "";
            Uri uri=data.getData();
            if(uri==null){
                return;
            }
            boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
            if(isKitKat && DocumentsContract.isDocumentUri(mContext, uri)){
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    String docId = DocumentsContract.getDocumentId(uri);
                    String[] split = docId.split(":");
                    String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        imagePath = Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {
                    String docId = DocumentsContract.getDocumentId(uri);
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                    imagePath = getImagePath(contentUri,null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    String docId = DocumentsContract.getDocumentId(uri);
                    String[] split = docId.split(":");
                    String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[] { split[1] };
                    imagePath = getImagePath(contentUri, selection, selectionArgs);
                }
            }else if("content".equalsIgnoreCase(uri.getScheme())){
                //如果是content类型的URI，则使用普通方式处理 （图库选取）
                imagePath = getImagePath(uri,null, null);
            }else if("file".equalsIgnoreCase(uri.getScheme())){
                //如果是file类型的Uri,直接获取图片路径即可（文件选取）
                imagePath = uri.getPath();
            }
            File file = new File(imagePath);
            if (isCrop) {
                startCrop(file);
            } else{
                if(mPhotoCallBack!=null){
                    mPhotoCallBack.callback(file);
                }
            }
//            if(file.exists()){
//                imageView.setImageBitmap(BitmapUtils.file2Bitmap(file, 1024, 1024));
//            }
        }
    }


    private String getImagePath(Uri uri, String selection, String[] selectionArgs) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = mContext.getContentResolver().query(uri, null, selection, selectionArgs, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
